package atm.zhaz.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.regex.Pattern;

public class Client {
	String host;
	int port;
	Socket server;
	String response = null;
	public static Pattern RESPONSE_PATTERN = Pattern
			.compile("~[a-zA-Z_-]+:[a-zA-Z0-9 .=-]*~");
	public static String REQUEST_FORMAT = "~%s:%s:%s:%s~";

	public Client(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public String speak_with_server(Scanner in, PrintWriter out, String request) {
		// say
		out.println(request);
		out.flush();

		// listen
		String line = in.findInLine(RESPONSE_PATTERN);
		if (line != null) {
			line = line.substring(1, line.length() - 1);
			return line;
		}
		return null;
	}

	public String sendRequest(String request) {
		try {
			response = null;
			server = new Socket(host, port);
			Scanner in = new Scanner(server.getInputStream());
			PrintWriter out = new PrintWriter(server.getOutputStream());
			response = speak_with_server(in, out, request);
			in.close();
			out.close();
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				System.out.println("Response is ready!");
		}
		return response;
	}
}
